<?php

declare(strict_types=1);

namespace App\Traits\Model\Admin;



use App\Request\FormRequest;
use Donjan\Casbin\Enforcer;
use Hyperf\Context\Context;
use Hyperf\Context\ApplicationContext;

trait Permission
{
    /**
     * 检查当前用户权限是否选中
     * @param $value
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getIsCheckAttribute($value)
    {
        $app = ApplicationContext::getContainer()->get(FormRequest::class)->appName();
        $infoName = "{$app}Info";
        $info = Context::get($infoName);
        if ($info['is_admin']) {
            return true;
        }
        $roles = Enforcer::getRolesForUserInDomain((string)$info['id'], $app);
        if (!$roles) {
            return false;
        }
        foreach ($roles as $role) {
            if (true === Enforcer::enforce((string)$role, $app, $this->path, $this->method)) {
                return true;
            }
        }
        return false;
    }
}
